package com.sqx.modules.health.controller;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import com.sqx.modules.health.common.Constants;
import com.sqx.modules.health.common.Result;
import com.sqx.modules.health.entity.NcgDeviceWatch;
import com.sqx.modules.health.entity.Record;
import com.sqx.modules.health.entity.Recordset;
import com.sqx.modules.sys.entity.SysUserEntity;
import com.sqx.modules.health.service.INcgDeviceWatchService;
import com.sqx.modules.health.service.IRecordService;
import com.sqx.modules.health.service.IRecordsetService;
import com.sqx.modules.health.service.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 设备使用记录 前端控制器
 * </p>
 *
 * @author gxy
 * @since 2022-07-28
 */

@Api(value = "设备使用记录", tags = "", description = "")
@RestController
@RequestMapping("/health/recordset")
public class RecordsetController {
    @Autowired
    private IRecordsetService recordsetService;
    @Autowired
    private IUserService userService;
    @Autowired
    private INcgDeviceWatchService watchService;
    @Autowired
    private IRecordService recordService;

    // 新增或更新
    @PostMapping("/save")
    @ApiOperation(value = "新增或更新设备使用记录", notes = "新增或更新设备使用记录")
    public Result save(@RequestBody Recordset recordset){
        return Result.success(recordsetService.save(recordset));
    }

    // 根据ID删除
    @DeleteMapping("/del/{id}")
    @ApiOperation(value = "根据ID删除设备使用记录", notes = "根据ID删除设备使用记录")
    public Result delete(@PathVariable Integer id){
        return Result.success(recordsetService.removeById(id));
    }

    // 根据IDS删除
    @PostMapping("/del/batch")
    @ApiOperation(value = "根据IDS删除设备使用记录", notes = "根据IDS删除设备使用记录")
    public Result deleteBatch(@RequestBody List<Integer> ids){
        return Result.success(recordsetService.removeByIds(ids));
    }

    // 查询全部
    @GetMapping("/findAll")
    @ApiOperation(value = "查询全部设备使用记录", notes = "查询全部设备使用记录")
    public Result findAll(){
        return Result.success(recordsetService.list());
    }

    // 根据ID查询一条记录
    @GetMapping("/findOne")
    @ApiOperation(value = "根据ID查询一条记录设备使用记录", notes = "根据ID查询一条记录设备使用记录")
    public Result findOne(@PathVariable Integer id){
        return Result.success(recordsetService.getById(id));
    }

    // 分页查询
    @GetMapping("/findPage")
    @ApiOperation(value = "分页查询设备使用记录", notes = "分页查询设备使用记录")
    public Result findPage(@RequestParam Integer pageNum,@RequestParam Integer pageSize,
                           @RequestParam(required = false,defaultValue = "")Long docid){
        QueryWrapper<Recordset> queryWrapper = new QueryWrapper<Recordset>()
                .eq(ObjectUtil.isNotEmpty(docid), "docid", docid)
                .orderByDesc("startdate");
        Page<Recordset> result = recordsetService.page(new Page<>(pageNum, pageSize), queryWrapper);
        result.getRecords().forEach(recordset -> {
            if (ObjectUtil.isNotEmpty(recordset.getUid())) {
                SysUserEntity user = userService.getRedisByUid(recordset.getUid());
                if(ObjectUtil.isNull(user))recordset.setUName("患者信息有误");
                recordset.setUName(ObjectUtil.isEmpty(user.getNickName()) ? user.getUsername() : user.getNickName());
            }
            if (ObjectUtil.isNotEmpty(recordset.getDocid())) {
                SysUserEntity user = userService.getRedisByUid(recordset.getDocid());
                if(ObjectUtil.isNull(user))recordset.setUName("患者信息有误");
                recordset.setDocName(ObjectUtil.isEmpty(user.getNickName()) ? user.getUsername() : user.getNickName());
            }
        });
        return  Result.success(result);
    }

    @Transactional(rollbackFor = Exception.class)
    @GetMapping("/deviceBack")
    public Result deviceBack(@RequestParam(required = false, defaultValue = "") @JsonSerialize(using = ToStringSerializer.class)Long id,
                             @RequestParam(required = false, defaultValue = "") String imei){
//        LambdaUpdateWrapper<Recordset> updateWrapper = new LambdaUpdateWrapper<Recordset>()
//                .set(Recordset::getStatus, 1)
//                .set(Recordset::getEnddate, LocalDateTime.now())
//                .eq(ObjectUtil.isNotEmpty(imei), Recordset::getImei, imei)
//                .eq(ObjectUtil.isNotEmpty(imei), Recordset::getImei, imei);
//        boolean update = recordsetService.update(updateWrapper);

        Recordset recordset = recordsetService.getLast(imei);
        recordset.setStatus(1);
        recordset.setEnddate(LocalDateTime.now());
        boolean update = recordsetService.saveOrUpdate(recordset);

        LambdaUpdateWrapper<NcgDeviceWatch> wrapper = new LambdaUpdateWrapper<NcgDeviceWatch>()
                .set(NcgDeviceWatch::getDoctorid, null)
                .set(NcgDeviceWatch::getUid, null)
                .set(NcgDeviceWatch::getStatus, 3)
                .eq(ObjectUtil.isNotEmpty(imei), NcgDeviceWatch::getImei, imei);
        boolean device = watchService.update(wrapper);

        Record record = recordService.getLastRecord(imei);
        record.setFlag(1);
        recordService.saveOrUpdate(record);

        if (device && update) {
            return Result.success("设备归还成功");
        } else {
            return Result.error(Constants.CODE_500, "归还失败,请联系管理员");
        }
    }

}

